<template>
  <div class="yd-bg-block" :style="{ 'background-image': 'url('+ydNormalBg+')', 'width': '100%', 'height': '100%'}">>
    <el-image :src="ydNormalBg" lazy fit="cover" style="position: absolute;width: 100%;height: 100%;top: 0;left:0;"></el-image>
    <div class="yd-form-block">
      <div class="yd-form-title">用户登录</div>
      <el-form :model="loginForm" ref="loginForm" :rules="loginRules" @keyup.enter.native="handleLogin">
        <el-form-item prop="username">
          <div class="yd-loginFormItem">
            <img src="../../assets/images/yonghuming.png" style="max-width: 8%;max-height: 8%;margin-left: 5px"/>
            <el-input v-model="loginForm.username" placeholder="请输入用户名" @focus="showBorderLeft('userNameBorder')" @blur="userNameBorder=false"/>
            <i class="el-icon-error" @click="clear" style="font-size: 18px;color: #F4F4F4"></i>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <div class="yd-loginFormItem">
            <img src="../../assets/images/mima.png" style="max-width: 8%;max-height: 8%;margin-left: 5px"/>
            <el-input v-model="loginForm.password" :type="showPassword?'':'password'" placeholder="请输入密码" @focus="showBorderLeft('passwordBorder')" @blur="passwordBorder=false"/>
            <svg-icon :icon-class="showPassword==false? 'eye' : 'eye-open'" @click="showPassword=!showPassword" style="color: #ebebeb"/>
          </div>
        </el-form-item>
        <el-form-item prop="verificationCode">
          <div class="yd-loginFormItem">
            <img src="../../assets/images/code.png" style="max-width: 8%;max-height: 8%;margin-left: 5px"/>
            <el-input v-model="loginForm.verificationCode" placeholder="请输入验证码" @focus="showBorderLeft('codeBorder')" @blur="codeBorder=false" style="width: 52%"/>
            <img :src="url" style="max-width: 100px;max-height: 100%" @click="initData"/>
          </div>
        </el-form-item>
        <el-form-item prop="agree">
          <div class="checkBoxItem">
            <el-checkbox v-model='loginForm.agree' class="checkboxStyle">我已审慎阅读并同意</el-checkbox>
            <span class="agreementItem" v-for="(item,index) in loginAgreementList" :key="index" @click="showAgreementDetail(item)" >《{{item.title}}》</span>
          </div>
        </el-form-item>
      </el-form>
      <div class="yd-form-btn" @click="handleLogin">
        <div class="yd-login-btn" :style="{'background-image': btnStyle}" >登录</div>
      </div>

    </div>
    <el-dialog
      :title="title"
      :visible.sync="showContentDialog"
      width="90%"
      center>
      <div v-html="agreementHtml" style="margin: 0 20px;"></div>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showContentDialog = false">关  闭</el-button>
        </span>
    </el-dialog>

    <el-dialog class="loginView" title="修改密码" top="20vh" :visible.sync="operation.loginView" :append-to-body="true"
               :width="$store.state.app.screenWidth<600?'100%':'500px'">
      <el-form ref="passwordForm"  :model="passwordForm" label-width="90px" :rules="rules">
        <el-form-item label="旧密码" prop="oldPassWord">
          <el-input v-model="passwordForm.oldPassWord" show-password ></el-input>
        </el-form-item>
        <el-form-item label="新密码"  prop="newPassWord">
          <el-input v-model="passwordForm.newPassWord" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="commitPassWord">
          <el-input v-model="passwordForm.commitPassWord" show-password ></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
      <el-button @click="showLoginView(false)" size="small">关 闭</el-button>
      <el-button @click="changePassWord" type="primary" size="small">确 认</el-button>
        <!--填写充值金额--></span>
    </el-dialog>

  </div>
</template>
<script>
import {bossLogin, initializationLogin, getAgentAgreement, getLoginAgreement,getUserLogin,changePassWordPersonal} from '@/api/getData'
export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassWord) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      // ydNormalBg: require('@/assets/login/yd-normal-bg.jpg'),
      ydNormalBg: require('@/assets/login/yd-normal.png'),
      ydNormalBody: '',
      btnStyle: 'linear-gradient(to top, #005bea 0%, #00c6fb 100%)',
      encryptedString: '',
      url: '',
      operation: {
        loginView: false,
        rechargeView: false,
      },
      loginForm: {
        username: '',
        password: '',
        verificationCode: '',
        agree: false,
      },
      loginRules: {
        username: [{required: true, trigger: 'blur', message: '请输入用户名'}],
        password: [{required: true, trigger: 'blur', validator: validatePass}],
        verificationCode: [{required: true, trigger: 'blur', message: '请输入图片验证码'}]
      },
      passwordForm:{
        oldPassWord: '',
        newPassWord: '',
        commitPassWord: ''
      },
      loading: false,
      pwdType: 'password',
      redirect: undefined,
      activeName: 'first',
      userNameBorder: false,
      passwordBorder: false,
      codeBorder: false,
      showPassword: false,
      imgList: [
        // { min: 1609776000000, max: 1609862400000,  bgImg: require('../../assets/login/yd-xiaohan.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #4D8DEC 0%, #90B8F3 100%)'},
        // { min: 1611072000000, max: 1611158400000,  bgImg: require('../../assets/login/yd-laba.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},
        // { min: 1612368000000, max: 1612454400000,  bgImg: require('../../assets/login/yd-xiaonian.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},
        // { min: 1612972800000, max: 1613059200000,  bgImg: require('../../assets/login/yd-chuxi.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//11
        // { min: 1613059200000, max: 1613145600000,  bgImg: require('../../assets/login/yd-chuyi.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//12
        // { min: 1613145600000, max: 1613232000000,  bgImg: require('../../assets/login/yd-chuer.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//13
        // { min: 1613232000000, max: 1613318400000,  bgImg: require('../../assets/login/yd-chusan.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//14
        // { min: 1613318400000, max: 1613404800000,  bgImg: require('../../assets/login/yd-chusi.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//15
        // { min: 1613404800000, max: 1613491200000,  bgImg: require('../../assets/login/yd-chuwu.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//16
        // { min: 1613491200000, max: 1613577600000,  bgImg: require('../../assets/login/yd-chuliu.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//17
        // { min: 1613577600000, max: 1613664000000,  bgImg: require('../../assets/login/yd-chuqi.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//18
        // { min: 1613664000000, max: 1613750400000,  bgImg: require('../../assets/login/yd-chuba.jpg'), bgBody: '',btnStyle: 'linear-gradient(to top, #a8071a 0%, #cf1322 100%)'},//19
      ],
      agreementHtml: '',
      showAgreementDialog: false,
      loginAgreementList: [],
      showContentDialog: false,
      title: '',
      themeInTime: false,
      oldPassWord: '',
      newPassWord: '',
      commitPassWord: '',
      form: {
      },
      rules: {
        oldPassWord: [
          { required: true, message: '请输入老密码', trigger: 'change' }
        ],
        newPassWord: [
          { required: true, message: '请输入新密码', trigger: 'change' },
          { pattern: /^(?!([a-zA-Z]+|\d+)$)[a-zA-Z\d]{6,20}$/, message: '请输入6-20位数字加字母！' }
        ],
        commitPassWord: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  mounted(){
    let current = new Date().getTime();
    for(let item of this.imgList){
      if(current>item.min&&current<item.max){
        this.ydNormalBg = item.bgImg;
        this.ydNormalBody = item.bgImg;
        this.btnStyle = item.btnStyle;
        this.themeInTime = true;
      }
    }
    this.initData()
  },
  methods:{
    showAgreementDetail(obj){
      this.title = obj.title;
      this.agreementHtml = obj.content;
      this.showContentDialog = true;
    },
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    async initData() {
      const returnData = await initializationLogin({})
      if (returnData._result) {
        this.encryptedString = returnData.data
        this.url = '/api/oceanside-send-and-check/code/send/pictureCode/' + this.encryptedString
      }
      let returnList = await getLoginAgreement({ dictType: 'LOGIN' })
      if(returnList._result){
        if(returnList.data){
          this.loginAgreementList = returnList.data;
        }
      }
    },

    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true;
          const t = await bossLogin({
            loginname: this.loginForm.username,
            password: this.loginForm.password,
            uid: this.encryptedString,
            imgCode: this.loginForm.verificationCode
          })

          if (t._result) {
            //判断主题是否在节日时间点内
            if(!this.themeInTime){
              //如果数据库查询到主题 直接覆盖缓存中的主题
              if(t.data.theme){
                let item = JSON.parse(t.data.theme);//数据库内存储的值
                let normalBg = document.body.style.getPropertyValue('--normalBg').trim();//APP.vue中存储的主题色
                if(item.normalBg!=normalBg){
                  window.name = 'login';
                  this.$store.dispatch('app/setSidebarBgColor', item.normalBg);
                  this.$store.dispatch('app/setTableBgColor', item.lBg);
                  localStorage.setItem('theme',t.data.theme);
                  // 设置值
                  document.body.style.setProperty("--normalBg", item.normalBg);
                  document.body.style.setProperty("--lightBg", item.lightBg);
                  document.body.style.setProperty("--hoverBg", item.hoverBg);
                  document.body.style.setProperty("--lbBg", item.lbBg);
                  document.body.style.setProperty("--lBg", item.lBg);
                  document.body.style.setProperty("--primary", item.normalBg);
                  document.body.style.setProperty("--primaryActive", item.lightBg);
                  document.body.style.setProperty("--primaryHover", item.hoverBg);
                  document.body.style.setProperty("--primaryHoverBg", item.lbBg);
                  document.body.style.setProperty("--success", "#25C547");
                  document.body.style.setProperty("--successActive", "#25C540");
                  document.body.style.setProperty("--successHover", "#6EDC91");
                  document.body.style.setProperty("--successHoverBg", "#E8F9EB");
                  document.body.style.setProperty("--warning", "#FCA00C");
                  document.body.style.setProperty("--warningActive", "#F19B1A");
                  document.body.style.setProperty("--warningHoverBg", "#F9F5EF");
                  document.body.style.setProperty("--info", "#CACACA");
                  document.body.style.setProperty("--infoActive", "#C0C0C0");
                  document.body.style.setProperty("--infoHoverBg", "#F8F8F8");
                  document.body.style.setProperty("--danger", "#DD1B1B");
                  document.body.style.setProperty("--dangerActive", "#D51B1B");
                  document.body.style.setProperty("--dangerHoverBg", "#FCEBEB");
                }
                else{
                  window.name = 'isFirstVisit';
                }
              }
            }

            // <======NoticeList======
            if (t.data.noticeList && t.data.noticeList.length > 0) {
              localStorage.setItem('noticeList', JSON.stringify(t.data.noticeList))
            } else {
              localStorage.setItem('noticeList', JSON.stringify([]))
            }
            // ======NoticeList======>
            localStorage.setItem('router', JSON.stringify(t.data.menuList))
            localStorage.setItem('permission', JSON.stringify(t.data.permissionList))
            localStorage.setItem('image', t.data.setting.IMG_READ_URL)
            localStorage.setItem('roleChar', t.data.roleChar)
            localStorage.setItem('sessionId',t.data.sessionId)


            this.$store.dispatch('user/Login', t.data).then(async () => {
              if(t.data.roleChar=='DAILI_ADMIN'){
                let res = await getAgentAgreement({})
                if(res._result){
                  if(res.data&&res.data.length>0){
                    localStorage.setItem('signStatus',false);
                    this.$store.dispatch('user/NeedToSignAgreement', false).then(() => {
                      this.$alert('您有未签署的代理协议，请尽快在电脑端登录审阅并签字', '重要提示', {
                        confirmButtonText: '确定',
                        callback: action => {
                          this.$router.push({path: '/'})
                        }
                      });
                    }).catch(() => {
                      this.loading = false
                    })
                  }
                  else{
                    localStorage.setItem('signStatus',true);
                    this.loading = false
                    this.$router.push({path: '/'})
                  }
                }
              }
              else{
                localStorage.setItem('signStatus',true);
                this.loading = false
                this.$router.push({path: '/'})
                // this.loading = false
                // this.$router.push({path: '/'})
              }
              // this.loading = false
              // this.$router.push({path: '/'})




            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
          this.initData()
        }
      })
    },
    toForgetPassword() {
      this.$router.push({path: '/password-retrieval'})
    },
    clear() {
      this.loginForm.username = '';
      this.loginForm.password = '';
    },
    showBorderLeft(name) {
      let arr = ['userNameBorder', 'passwordBorder', 'codeBorder'];
      for (let i of arr) {
        if (name == i) {
          this[i] = true;
        } else {
          this[i] = false;
        }
      }
    },
    async showLoginView(boolean) {
      this.operation.loginView = boolean
    },
    async changePassWord() {
      this.$refs['passwordForm'].validate(async (valid) => {
        if (valid) {
          const returnData = await changePassWordPersonal({
            id: this.form.loginId,
            oldPassWord: this.passwordForm.oldPassWord,
            newPassWord: this.passwordForm.newPassWord,
            commitPassWord: this.passwordForm.commitPassWord
          })
          if (returnData._result) {
            this.$message.success("操作成功");
            this.operation.loginView = false
          }
          return true;
        } else {
          console.log('error submit!!');
          return false;
        }

      });
    },
  }
}
</script>
<style lang="scss" scoped>
/*移动端登录样式*/
.yd-bg-block{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  //background: radial-gradient(at center, #C40909, #5C0404);
  //background-size: contain;
  //background: #0075c3;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
.ydBgImg{
  /*width: 100%;
  height: 100%;*/
  height: 100%;
  width: auto;
  z-index: 10;
}
.yd-form-block{
  width: 90%;
  height: auto;
  position: relative;
  top: 0;
  left: 0;
  //top: 25%;
  //left: 5%;
  background: rgba(255,255,255,0.2);
  z-index: 100;
  border-radius: 5px;
  box-shadow: 10px 12px 12px 10px rgba(0, 0, 0, 0.1);
  padding: 5%;
}
.yd-form-title{
  width: 90%;
  height: 20%;
  position: relative;
  top: 0;
  left: 5%;
  display: flex;
  align-items: center;
  font-size: 22px;
  color: #fff !important;
  margin-bottom: 20px;
}
.yd-loginFormItem{
  width: 90%;
  height: 15%;
  position: relative;
  top: 0;
  left: 5%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
  border-radius: 5px;
  box-shadow: 10px 12px 12px 10px rgba(0, 0, 0, 0.1);
}
.yd-form-btn{
  width: 100%;
  height: 20%;
  position: relative;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.yd-login-btn{
  width: 90%;
  height: 40px;
  position: relative;
  border: none;
  border-radius: 5px;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
  letter-spacing: 10px;
  margin: 0 5%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}
.checkboxStyle{
  color: white;
}

.checkBoxItem{
  width: 100%;
  height: auto;
  position: relative;
  top: 0;
  left: 0;
  line-height: 25px;
  margin: 10px 0;
  text-align: left;
}
.agreementItem{
  width: auto;
  padding: 0 5px 0 10px;
  color: crimson;
  cursor: pointer;
}
.agreementItem:hover{
  font-weight: bold;
  color: white;
}
>>> .el-input {
  width: 80%;
  background: rgba(255,255,255,0);
}

>>> .el-input--medium .el-input__inner {
  height: 46px;
  line-height: 46px;
  border: none;
}

>>> .el-form-item__error {
  left: 55px;
}
>>> .el-input--medium .el-input__inner {
  height: 46px;
  line-height: 46px;
  background: none;
  border: none;
  color: #333 !important;
  font-size: 20px;
}

>>>input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill {
  -webkit-text-fill-color: #333 !important;
  background-color: transparent;
  transition: background-color 50000s ease-in-out 0s;
}
</style>
